package com.hmdp.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.RedisConstants.LOCK_SHOP_KEY;

@Component
public class CacheClient {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService executorService = Executors.newFixedThreadPool(10);

    //方法1，将任意java对象序列化为json，再保存到string类型的key中，并且可以设置过期时间
    public void setWithExpiration(String key, Object value, Long time, TimeUnit unit){
        //1.将数据转为json
        String jsonStr = JSONUtil.toJsonStr(value);
        //2.保存到redis
        stringRedisTemplate.opsForValue().set(key,jsonStr,time,unit);
    }
    //方法2. 将任意java对象序列化为json，再保存到string类型的key中，并且可以设置逻辑过期时间，用于处理缓存击穿问题
    public void setWithLogicalExpire(String key, Object value, Long time){
        //1.将数据转为json
        String jsonStr = JSONUtil.toJsonStr(value);
        //2.保存到redis
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(time));
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }
    //方法3. 根据指定key查询缓存，并反序列化为指定类型，利用缓存空值的方式解决缓存穿透问题
    public <R, ID> R cachePenetratio(ID id, Class<R> clazz, String keyPrefix, Function<ID, R> dbFallback, Long time, TimeUnit unit){
        //1.从redis查询
        String s = stringRedisTemplate.opsForValue().get(keyPrefix + id);
        //2.判断是否存在
        if (StrUtil.isNotBlank(s)){
            //存在
            return JSONUtil.toBean(s, clazz);
        }
        if (s != null) {
            //是空值，返回错误
            return null;
        }
        //4.不存在，根据id查询数据库
        R r = dbFallback.apply(id);
        //5.数据库不存在，返回错误
        if (r == null){
            //将空值写入redis
            stringRedisTemplate.opsForValue().set(keyPrefix + id, "", RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        //6.存在，写入redis
        setWithExpiration(keyPrefix + id, r, time, unit);
        //7.返回
        return r;
    }

    //方法4. 根据指定key查询缓存，并反序列化为指定类型，利用逻辑过期解决缓存击穿问题
    public <R,ID> R logicalExpiration(ID id, Class<R> clazz, String keyPrefix, Function<ID, R> dbFallback){
        //1.从redis查询
        String s = stringRedisTemplate.opsForValue().get(keyPrefix + id);
        if (StrUtil.isBlank(s)){
            return null;
        }
        //2.拿到缓存
        RedisData redisData = JSONUtil.toBean(s, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        JSONObject data = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(data, clazz);
        //3.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())){
            //未过期，直接返回店铺信息
            return r;
        }
        //5.已过期，获取互斥锁
        if (tryLock(LOCK_SHOP_KEY+id)){
            //6.获取锁成功开启新线程，查询数据库，写入redis
            //再次检查缓存是否过期
            if (expireTime.isAfter(LocalDateTime.now())){
                //未过期，直接返回店铺信息，不用再查数据库了
                return r;
            }
            executorService.submit(()->{
                try {
                    //查询数据库
                    R r1 = dbFallback.apply(id);
                    //重写redis
                    setWithLogicalExpire(keyPrefix + id, r1, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    //7.释放锁
                    unLock(LOCK_SHOP_KEY+id);
                }
            });
        }
        //未获取，返回信息优惠卷
        return r;

    }

    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }

    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
}
